/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bm.library.Info;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.chatRow.BaseChatRow;
import com.srwl.mytx.widget.chatRow.ChatRowImage;
import com.srwl.mytx.widget.chatRow.ChatRowLocation;
import com.srwl.mytx.widget.chatRow.ChatRowRedPacket;
import com.srwl.mytx.widget.chatRow.ChatRowText;
import com.srwl.mytx.widget.chatRow.ChatRowTransfer;
import com.srwl.mytx.widget.chatRow.ChatRowVideo;
import com.srwl.mytx.widget.chatRow.ChatRowVoice;

import java.util.ArrayList;
import java.util.List;


public class MyMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final static String TAG = "msg";
    private static final int DEFAULT_LOAD_COUNT = 15;
    private static final int HEADER_PLACE = 1;

    private Context context;

    private static final int ITEM_TYPE_LOADING = 100;

    private static final int MESSAGE_TYPE_RECV_TXT = 0;
    private static final int MESSAGE_TYPE_SENT_TXT = 1;
    private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
    private static final int MESSAGE_TYPE_SENT_LOCATION = 3;
    private static final int MESSAGE_TYPE_RECV_LOCATION = 4;
    private static final int MESSAGE_TYPE_RECV_IMAGE = 5;
    private static final int MESSAGE_TYPE_SENT_VOICE = 6;
    private static final int MESSAGE_TYPE_RECV_VOICE = 7;
    private static final int MESSAGE_TYPE_SENT_VIDEO = 8;
    private static final int MESSAGE_TYPE_RECV_VIDEO = 9;
    private static final int MESSAGE_TYPE_SENT_FILE = 10;
    private static final int MESSAGE_TYPE_RECV_FILE = 11;
    private static final int MESSAGE_TYPE_SENT_EXPRESSION = 12;
    private static final int MESSAGE_TYPE_RECV_EXPRESSION = 13;
    public static final int MESSAGE_TYPE_SENT_RED_PACKET = 14;
    public static final int MESSAGE_TYPE_RECV_RED_PACKET = 15;
    public static final int MESSAGE_TYPE_SENT_TRANSFER = 16;
    private static final int MESSAGE_TYPE_RECV_TRANSFER = 17;
    public static final int MESSAGE_TYPE__RED_PACKET_ACK = 18;//红包回执，发送回执方不显示，暂时不写红包回执，红包回执可以考虑，用“已读/未读’--来改为已领取，未领取，
    private boolean showHeader;
    private boolean showFooter;


    private User targetUser;
    private LayoutInflater inflater;
    private MessageListItemClickListener itemClickListener;
    private List<Message> messageList = new ArrayList<>();
    private BaseChatRow.ChatRowCallBack chatRowCallBack;
    private String myId;
    private boolean scrolling;


    public MyMessageAdapter(Context context, User targetUser, List<Message> messageList) {
        this.context = context;
        this.targetUser = targetUser;
        this.messageList = messageList;

        inflater = LayoutInflater.from(context);
        myId = UserProfileManager.getInstance().getLoginUserInfo().getuId();


    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case MESSAGE_TYPE_SENT_TXT:
                View textSendView = inflater.inflate(R.layout.ease_row_sent_text, parent, false);
                return new ChatRowText(textSendView);
            case MESSAGE_TYPE_RECV_TXT:
                View textReceivedView = inflater.inflate(R.layout.ease_row_received_text, parent, false);
                return new ChatRowText(textReceivedView);
            case MESSAGE_TYPE_SENT_VOICE:
                View voiceSentView = inflater.inflate(R.layout.ease_row_sent_voice, parent, false);
                return new ChatRowVoice(voiceSentView);
            case MESSAGE_TYPE_RECV_VOICE:
                View voiceReceivedView = inflater.inflate(R.layout.ease_row_received_voice, parent, false);
                return new ChatRowVoice(voiceReceivedView);
            case MESSAGE_TYPE_SENT_IMAGE:
                View imageSentView = inflater.inflate(R.layout.ease_row_sent_picture, parent, false);
                return new ChatRowImage(imageSentView);
            case MESSAGE_TYPE_RECV_IMAGE:
                View imageReceiveView = inflater.inflate(R.layout.ease_row_received_picture, parent, false);
                return new ChatRowImage(imageReceiveView);
            case MESSAGE_TYPE_SENT_VIDEO:
                View videoSentView = inflater.inflate(R.layout.ease_row_sent_video, parent, false);
                return new ChatRowVideo(videoSentView);
            case MESSAGE_TYPE_RECV_VIDEO:
                View videoReceiveView = inflater.inflate(R.layout.ease_row_received_video, parent, false);
                return new ChatRowVideo(videoReceiveView);
            case MESSAGE_TYPE_SENT_LOCATION:
                View locationSentView = inflater.inflate(R.layout.ease_row_sent_location, parent, false);
                return new ChatRowLocation(locationSentView);
            case MESSAGE_TYPE_RECV_LOCATION:
                View locationReceiveView = inflater.inflate(R.layout.ease_row_received_location, parent, false);
                return new ChatRowLocation(locationReceiveView);
            case MESSAGE_TYPE_SENT_RED_PACKET:
                View redPacketSentView = inflater.inflate(R.layout.em_row_sent_red_packet, parent, false);
                return new ChatRowRedPacket(redPacketSentView);
            case MESSAGE_TYPE_RECV_RED_PACKET:
                View redPacketReceiveView = inflater.inflate(R.layout.em_row_received_red_packet, parent, false);
                return new ChatRowRedPacket(redPacketReceiveView);
            case MESSAGE_TYPE_SENT_TRANSFER:
                View transferSentView = inflater.inflate(R.layout.em_row_sent_transfer, parent, false);
                return new ChatRowTransfer(transferSentView);
            case MESSAGE_TYPE_RECV_TRANSFER:
                View transferReceiveView = inflater.inflate(R.layout.em_row_received_transfer, parent, false);
                return new ChatRowTransfer(transferReceiveView);
            case ITEM_TYPE_LOADING:
                View header = inflater.inflate(R.layout.chat_message_load_data_header_layout, parent, false);
                return new LoadingDateViewHolder(header);
        }

        return null;

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

//        if (holder instanceof LoadingDateViewHolder) {
//            return;
//        }
//
//        if (showHeader) {
//            position = position - HEADER_PLACE;
//        }
//        if (scrolling) {
//            Glide.with(context).pauseRequests();
//        } else {
//            Glide.with(context).resumeRequests();
//        }
        Message message = messageList.get(position);
        BaseChatRow chatRow = (BaseChatRow) holder;
        chatRow.setChatRowCallBack(chatRowCallBack);//先设置 回调，再调用 setUpView（）， 否则可能出现 需要更新消息状态的时候，chatRowCallBack 为空
        chatRow.setUpView(context, message, this, itemClickListener, targetUser, position);

    }


    @Override
    public int getItemCount() {
//        if (showHeader || showFooter) {
//            return messageList.size() + HEADER_PLACE;
//        }
        return messageList.size();
    }


    public int getItemViewType(int position) {
//        if (showHeader && position == 0) {
//            return ITEM_TYPE_LOADING;
//        }
//
//        if (showFooter && position == messageList.size()) {
//            return ITEM_TYPE_LOADING;
//        }
//        if (showHeader){
//            position=position-HEADER_PLACE;
//        }
        Message message = messageList.get(position);
        boolean isSendMessage = Utils.isSendMessage(message);
        Integer messageType = message.getSubType();
        if (messageType == Constant.IM_TYPE_TEXT) {
            return isSendMessage ? MESSAGE_TYPE_SENT_TXT : MESSAGE_TYPE_RECV_TXT;
        }
        if (messageType == Constant.IM_TYPE_IMAGE) {
            return isSendMessage ? MESSAGE_TYPE_SENT_IMAGE : MESSAGE_TYPE_RECV_IMAGE;
        }
        if (messageType == Constant.IM_TYPE_AUDIO) {
            return isSendMessage ? MESSAGE_TYPE_SENT_VOICE : MESSAGE_TYPE_RECV_VOICE;
        }
        if (messageType == Constant.IM_TYPE_VIDEO) {
            return isSendMessage ? MESSAGE_TYPE_SENT_VIDEO : MESSAGE_TYPE_RECV_VIDEO;
        }
        if (messageType == Constant.IM_TYPE_GEO) {
            return isSendMessage ? MESSAGE_TYPE_SENT_LOCATION : MESSAGE_TYPE_RECV_LOCATION;
        }
        if (messageType == Constant.IM_TYPE_COUPON) {
            return isSendMessage ? MESSAGE_TYPE_SENT_RED_PACKET : MESSAGE_TYPE_RECV_RED_PACKET;
        }
        if (messageType == Constant.IM_TYPE_TRANSFER) {
            return isSendMessage ? MESSAGE_TYPE_SENT_TRANSFER : MESSAGE_TYPE_RECV_TRANSFER;
        }


        Log.e(TAG, "getItemViewType:有消息类型没有匹配 "+message.toString() );
        return messageType;
    }


    public void setChatRowCallBack(BaseChatRow.ChatRowCallBack chatRowCallBack) {
        this.chatRowCallBack = chatRowCallBack;
    }

    public void setItemClickListener(MessageListItemClickListener listener) {
        itemClickListener = listener;
    }

    public void refresh(User targetUser) {
        this.targetUser = targetUser;
        notifyDataSetChanged();
    }

    public boolean isSendMessage(Message message) {
        return message.getFromId().equals(myId);
    }

    public void showFooter() {
        showFooter = true;
        notifyItemInserted(messageList.size());
    }

    public void hideFooter() {
        showFooter = false;
        notifyItemRemoved(messageList.size());
    }

    public void showHeader() {
        showHeader = true;
        notifyItemInserted(0);
    }

    public void hideHeader() {
        showHeader = false;
        notifyItemRemoved(0);
    }

    public void loadingComplete() {
        if (showHeader) {
            hideHeader();
        }
        if (showFooter) {
            hideFooter();
        }
    }

    public void setScrolling(boolean scrolling) {
        this.scrolling = scrolling;
    }

    public boolean isScrolling() {
        return scrolling;
    }

    class LoadingDateViewHolder extends RecyclerView.ViewHolder {

        public LoadingDateViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public interface MessageListItemClickListener {
        void onResendClick(Message message);

        boolean onBubbleClick(Message message);

        void onBubbleLongClick(Message message);

        void onUserAvatarClick(String userId);

        void onUserAvatarLongClick(String username);

        void onImageOrVideoRowClick(int position, Info imageInfo);
    }


}
